package com.albert.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Base64;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author lm
 * @desc
 * @date 2019/3/22 13:18
 **/
@Component
@Slf4j
public class HttpClientAuthUtils {

    private CloseableHttpClient httpClient;
    private RequestConfig requestConfig;


    private String userName;


    private String password;
    public HttpClientAuthUtils() {
        this.httpClient = HttpClients.createDefault();
        this.requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000).setSocketTimeout(30000)
                .setConnectTimeout(30000).build();
    }

    /**
     * Get调用MES接口数据
     *
     * @param url
     * @param params
     * @param headerParam
     * @return
     */
    public String sendGet(String url, Map<String, Object> params, Map<String, String> headerParam) {
        try {
            if (StringUtils.isEmpty(url)) {
                return "";
            }
            System.out.println("最初路径"+url);
            URIBuilder uriBuilder = new URIBuilder(url);
            // 请求参数
            if (params != null) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
                    System.out.println("数值String"+entry.getValue().toString());
                }
            }
            System.out.println("路径和参数"+uriBuilder);
            // 创建httpGet对象，设置url请求地址
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.setHeader("Accept", "application/json;charset=utf-8");

            // 连接超时配置30s
            httpGet.setConfig(this.requestConfig);
            // 用户名 + : + 密码转换后的base64加密文件
            String userName = headerParam.get("userName");
            String password = headerParam.get("password");
            String author = userName + ":" + password;
            // 转换成base64密文  数据格式 Basic空格+密文串
            httpGet.setHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString(author.getBytes()));
            if (null != headerParam) {
                for (Map.Entry<String, String> header : headerParam.entrySet()) {
                    httpGet.setHeader(header.getKey(), header.getValue());
                }
            }
            CloseableHttpResponse response = this.httpClient.execute(httpGet);
            // 解析结果，封装返回对象httpResult
            if (response.getEntity() != null) {
                HttpResult httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                        response.getEntity(), "UTF-8"));
                if (200 == httpResult.getCode()) {
                    return httpResult.getBody();
                }
            }
        } catch (URISyntaxException | IOException e) {
            log.error("httpGetError:" + url, e.toString());
        }
        return "";
    }

    /**
     * POST调用MES接口数据 生成维修工单
     *
     * @param url
     * @param headerParam
     * @return
     */
    public String sendPost(String url, Map<String, String> headerParam) {
        try {
            if (StringUtils.isEmpty(url)) {
                return "";
            }

            URIBuilder uriBuilder = new URIBuilder(url);

            //请求参数
            uriBuilder.setParameter("reqFrom", "oms");
            uriBuilder.setParameter("reqId", UUID.randomUUID().toString().replace("-", ""));
            uriBuilder.setParameter("reqTime", DateUtils.dateToString(new Date(), DateUtils.TIME));

            HttpPost httpPost = new HttpPost(uriBuilder.build());
            httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
            // 连接超时配置30s
            httpPost.setConfig(this.requestConfig);
            // 用户名 + : + 密码转换后的base64加密文件
            String author = userName + ":" + password;
            // 转换成base64密文  数据格式 Basic空格+密文串
            httpPost.setHeader("Authorization", "Basic " + Base64.getEncoder().encodeToString(author.getBytes()));
            if (null != headerParam) {
                for (Map.Entry<String, String> header : headerParam.entrySet()) {
                    httpPost.setHeader(header.getKey(), header.getValue());
                }
            }

            CloseableHttpResponse response = this.httpClient.execute(httpPost);
            if (response.getEntity() != null) {
                HttpResult httpResult = new HttpResult(response.getStatusLine().getStatusCode(), EntityUtils.toString(
                        response.getEntity(), "UTF-8"));
                if (200 == httpResult.getCode()) {
                    return httpResult.getBody();
                }
            }
        } catch (URISyntaxException | IOException e) {
            log.error("httpPostError:" + url, e.toString());
        }
        return "";
    }
}
